package top.likeqc.moneymark.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import top.likeqc.moneymark.entity.Bill;
import top.likeqc.moneymark.entity.Catename;
import top.likeqc.moneymark.mapper.BillMapper;
import top.likeqc.moneymark.mapper.CatenameMapper;
import top.likeqc.moneymark.service.CatenameService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.likeqc.moneymark.util.ShiroUtil;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author likeqc.top
 * @since 2021-07-03
 */
@Service
public class CatenameServiceImpl extends ServiceImpl<CatenameMapper, Catename> implements CatenameService {

    @Autowired CatenameMapper catenameMapper;
    @Autowired BillMapper billMapper;

    @Override
    @Transactional
    public void deleteById(Integer id, Integer newId) {
        Integer userid = ShiroUtil.getProfile().getId();
        if (newId != null) {
            Catename catename = catenameMapper.selectById(newId);
            Assert.isTrue(userid.equals(catename.getUserId()), "你不用 id="+newId+" 的拥有者");
        } else {
            Catename defaulCatename = catenameMapper.selectOne(new QueryWrapper<Catename>().eq("user_id", userid).eq("name", "默认分类"));
            if (defaulCatename == null) {
                defaulCatename = new Catename();
                defaulCatename.setUserId(userid);
                defaulCatename.setTypeId(catenameMapper.selectById(id).getTypeId());
                defaulCatename.setName("默认分类");
                catenameMapper.insert(defaulCatename);
            }
            newId = defaulCatename.getId();
        }
        UpdateWrapper<Bill> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userid);
        updateWrapper.eq("catename_id", id);
        updateWrapper.set("catename_id", newId);
        billMapper.update(null, updateWrapper);
        catenameMapper.deleteById(id);
    }
}
